/**
 * created by zhouli on 2018/12/20
 */
import config from 'config';
import React from 'react';
import httpFetch from 'share/httpFetch';
import errorMessage from 'share/errorMessage';
import ListTranformTree from 'components/method/listTransfromTree'
import {message, Icon} from 'antd';
import iconEye from "images/permission-setting/icon_read.png";
import {deepFullCopy, messages, sortByProperty} from "share/common";


export default {
  //对菜单列表排序
  sortMenuList(menuList, sortKey) {
    let hasOrder = [],
        hasNoOrder = [];
    menuList.forEach((item => {

      if (!item.resourceCreatedDate && item.createdDate) {
        item.resourceCreatedDate= new Date(item.createdDate).getTime();
      }
      if (typeof item.resourceOrder === 'number') {
        hasOrder.push(item);
      } else {
        hasNoOrder.push(item);
      }
    }))

    // 先以时间排序
    hasOrder= sortByProperty(hasOrder, 'resourceCreatedDate');
    let hasOrdered = sortByProperty(hasOrder, sortKey);
    //对于没有设置序号的，直接以时间排序
    let hasNoOrdered = sortByProperty(hasNoOrder, 'resourceCreatedDate');
    return [...hasOrdered, ...hasNoOrdered];
  },
  // 职能权限所有资源细项(职能对应的菜单树)
  getPermissionTree(params) {
    // let params = {
    //   permissionId:"1077167530856054786"
    // }
    return new Promise((resolve, reject) => {
      httpFetch.get(config.baseUrl + '/api/security/permission/resource/detail', params)
        .then((response) => {
          resolve(response)
        })
        .catch(function (err) {
          errorMessage(err.response);
          reject(err.response);
        })
    })
  },
  // 所有资源细项(所有菜单对应的菜单树)
  // 根据父id获取资源列表，不传默认根路径(不含职能权限读写权限的列表)
  getAllPermissionTree(params) {
    // let params = {
    //   resourceId: "1077167530856054786" ,
    //   roleType: "",
    //   categoryType: ""
    // }
    // resourceId ：0 是全部
    // categoryType 不传,默认就是全部
    // categoryType 职能权限大类，ADMIN:管理员可分配的 ， FINANCE:财务可分配的  OTHER:其他可分配的
    //todo
    //可以考虑用缓存，一旦一个类别的菜单被加载过，就缓存一下，可以强制刷新清除缓存
    return new Promise((resolve, reject) => {
      httpFetch.get(config.baseUrl + '/api/security/resource/list', params)
        .then((response) => {
          resolve(response)
        })
        .catch(function (err) {
          errorMessage(err.response);
          reject(err.response);
        })
    })
  },


  /*
  * 合并处理菜单
  * /api/security/resource/list  为当前角色 所有可以分配的菜单
  * /api/security/permission/resource/detail 为当前角色 已经分配过的菜单
  * 现在把这两个对象进行合并，把分配过的打上标记，返回所有可以分配的菜单
  * */
  mergeAllMenus(getAllPermissionTreeParams, getPermissionTreeParams) {
    let that = this;
    return new Promise((resolve, reject) => {
      Promise.all([
        that.getAllPermissionTree(getAllPermissionTreeParams),
        that.getPermissionTree(getPermissionTreeParams)
      ])
        .then(res => {
          console.log('mergeAllMenus')
          let allPermissionTree = res[0];
          let permissionTree = res[1];
          //统一转树
          let allPermissionTreeInstance = that.treeTranformTree(allPermissionTree.data.children);
          let permissionTreeInstance = that.listTranformTree(permissionTree.data.funcPermissionDetailDTOS);
          //统一获取列表
          let allList = allPermissionTreeInstance.getOrigin();
          //todo 拷贝一份 checkedList 方便用户挑选出新添加的，取消勾选的
          let checkedList = permissionTreeInstance.getOrigin();
          //返回列表，带有勾选标记
          let allWithCheckedList = that._getCheckedMenus(deepFullCopy(allList), deepFullCopy(checkedList));
          //转为树
          resolve([allWithCheckedList, deepFullCopy(checkedList)])
        })
        .catch((error) => {
          let err = {
            message: messages('permission-setting.key97')/*获取菜单异常，请刷新重试*/
          }
          errorMessage(err);
          reject(err);
        })
    })
  },

  //
  /*
  * 1.把已经分配过的打上标记
  * 2.由于分配过的菜单 与 没有被分配的菜单 对象属性不一样，这里用分配过的覆盖没有被分配的
  * */
  _getCheckedMenus(allList, checkedList) {
    const checkedListKeyMaps = checkedList.reduce((result, item, index) => {
      result[item._originKey]= item
      return result
    }, {});
     allList.map(item => {
      let checkItem = this._hasResourceId(item, checkedList, 'key');
      if (checkedListKeyMaps[item._originKey]) {
        const checkItem= checkedListKeyMaps[item._originKey]
        if (checkItem) {
          item.__checked = true;
          item.defaultReadable = checkItem.defaultReadable;
          item.__checkedId = checkItem.id;
          item.operationType = checkItem.operationType;
        }
      }
      return item
    });
    return allList;
  },

  //判断 item 是否在 checkedList 里面,以属性key判断
  _hasResourceId(item, checkedList, key) {
    for (let i = 0, len = checkedList.length; i < len; i++) {
      if (checkedList[i][key] === item[key]) {
        return checkedList[i];
      }
    }
  },
  //
  /*
  * 获取将被新增的菜单
  * @param originCheckedList 原本被勾选的
  * @param currentCheckedList 现在被勾选的
  * @return 返回结果结果列表
  * */
  getWillCheckedList(originCheckedList, currentCheckedList) {
    let list = [];
    currentCheckedList.map(item => {
      let checkItem = this._hasResourceId(item, originCheckedList, 'resourceId');
      //没有在原本已经添加过的菜单列表
      if (!checkItem) {
        list.push(item)
      }
    });
    return list
  },
  /*
  * 获取将被删除的的菜单
  * @param originCheckedList 原本被勾选的
  * @param currentUnCheckedList 现在没有被勾选的
  * @return 返回结果结果列表
  * */
  getWillDeletedList(originCheckedList, currentUnCheckedList) {
    let list = [];
    currentUnCheckedList.map(item => {
      let checkItem = this._hasResourceId(item, originCheckedList, 'resourceId');
      //在已经被添加过的菜单
      if (checkItem) {
        list.push(item)
      }
    });
    return list
  },
  /*
   *
   * @param item 菜单
   * @param onUnChecked 删除菜单
   * @param onChecked 添加菜单
   * @param editAble 是否有checked
   * */
  // let options = {
  //   item,
  //   onUnChecked,
  //   onChecked
  //   editAble
  // }
  getRegisterNodeTitle(options) {
    let {item, onUnChecked, onChecked, editAble} = options;
    let className = item._filter ? 'filter-class' : '';
    let wrapClass = item.__checked ? '' : 'disabled-tree-item'
    let title = <span className={className}>{item.title}</span>;
    let checkBtn = null;
    let icon = null;
    // 处理只有叶子节点可以被用来勾选
    if (editAble) {
      wrapClass = '';
      if (!item.children) {
        if (item.__checked) {
          checkBtn = <span className='async-btn async-btn-mask'
                         onClick={() => {
                           onUnChecked(item)
                         }}/>
        } else {
          checkBtn = <span className='async-btn'
                         onClick={() => {
                           onChecked(item)
                         }}/>
        }
      }

    }
    if (item.operationType === "RW") {
      icon = <span><Icon type="edit"/></span>;
    } else {
      icon = <span><img className="icon-eye" src={iconEye}/></span>
    }
    return (<div className={wrapClass}>{checkBtn}{title}&nbsp;{icon}</div>)
  },
  // POST 新建功能权限细项
  // 有了下面的批量接口，此接口可以不用
  createPermissionTreeNode(roleNode) {
    // let roleNode = {
    //   "permissionId": 1077167530856054786,
    //   "tenantId":985801821654523905,
    //   "resourceId":101001,
    //   "operationType":"RW",
    //   "enabled":true
    // }
    return new Promise((resolve, reject) => {
      httpFetch.post(config.baseUrl + '/api/security/permission/func', roleNode)
        .then((response) => {
          resolve(response)
        })
        .catch(function (err) {
          errorMessage(err.response);
          reject(err.response);
        })
    })
  },
  // POST 新建功能权限细项
  createPermissionTreeNodeBatch(roleNodeList) {
    // let roleNode = [{
    //   "permissionId": 1077167530856054786,
    //   "tenantId":985801821654523905,
    //   "resourceId":101001,
    //   "operationType":"RW",
    //   "enabled":true
    // }]
    return new Promise((resolve, reject) => {
      httpFetch.post(config.baseUrl + '/api/security/permission/func/batch', roleNodeList)
        .then((response) => {
          resolve(response)
        })
        .catch(function (err) {
          errorMessage(err.response);
          reject(err.response);
        })
    })
  },
  updatePermissionTreeNode(roleNode) {
    // let roleNode = {
    //   "id": "1078542983030263810",
    //   "createdDate": "2018-12-28T06:47:40Z",
    //   "lastModifiedDate": "2018-12-28T06:47:40Z",
    //   "createdBy": "0323234a-4667-4b6a-a141-5b73a15a7d60",
    //   "lastModifiedBy": "0323234a-4667-4b6a-a141-5b73a15a7d60",
    //   "tenantId": "985801821654523905",
    //   "resourceId": "101001",
    //   "permissionId": "1077167530856054786",
    //   "operationType": "R",
    //   "enabled": true,
    //   "deleted": null
    // }
    roleNode.id = roleNode.__checkedId ? roleNode.__checkedId : roleNode.id;
    return new Promise((resolve, reject) => {
      httpFetch.put(config.baseUrl + '/api/security/permission/func', roleNode)
        .then((response) => {
          resolve(response)
        })
        .catch(function (err) {
          errorMessage(err.response);
          reject(err.response);
        })
    })
  },
  //批量删除菜单
  deletePermissionTreeNodeBatch(ids) {
    return new Promise((resolve, reject) => {
      httpFetch.delete(config.baseUrl + '/api/security/permission/func/batch', ids)
        .then((response) => {
          resolve(response)
        })
        .catch(function (err) {
          errorMessage(err.response);
          reject(err.response);
        })
    })
  },
  /*
  * 有了批量删除删除
  * @departed
  * */
  deletePermissionTreeNode(id) {
    return new Promise((resolve, reject) => {
      httpFetch.delete(config.baseUrl + '/api/security/permission/func/id?id=' + id)
        .then((response) => {
          resolve(response)
        })
        .catch(function (err) {
          errorMessage(err.response);
          reject(err.response);
        })
    })
  },
  //列表转树
  //不同职能对应的功能，后端返回的是列表，需要前端转换为树
  listTranformTree(list) {
    //使用方式
    // 参数
    let options = {
      originType: 'list',//tree
      originList: list,
      topNodeId: '0',//默认顶级节点没有parentId
      limitKeys: [],//只要某些节点,todo
      filterKey: 'resourceName',//过滤的时候，匹配的字段
    }
    //节点配置
    let nodeConfig = {
      key: "resourceId",
      title: "resourceName",
    }
    console.error('listTranformTree1')
    return new ListTranformTree(options, nodeConfig);
  },
  treeTranformTree(list) {
    //使用方式
    // 参数
    let options = {
      originType: 'tree',//tree
      originList: list,
      topNodeId: '0',//默认顶级节点没有parentId
      limitKeys: [],//只要某些节点,todo
      filterKey: 'resourceName',//过滤的时候，匹配的字段
    }
    //节点配置
    let nodeConfig = {
      key: "resourceId",
      title: "resourceName",
    }
    console.error('listTranformTree2')
    return new ListTranformTree(options, nodeConfig);
  }

}
